﻿using System;
using System.Collections.Generic;
using System.Linq;
using WCF.NinjectDependencyInjectionDemo.Core;
using WCF.NinjectDependencyInjectionDemo.Models;

namespace WCF.NinjectDependencyInjectionDemo.Repositories
{
    public interface IContactRepository 
    {
        List<Contact> GetAll();
        Contact GetById(int id);
        void Save(Contact contact);
        void Remove(int id);
    }

    public class ContactRepository : IContactRepository
    {
        protected ICache Cache { get; set; }
        protected string CacheKey { get { return GetType().FullName; } }

        public ContactRepository(ICache cache)
        {
            Cache = cache;
        }

        public List<Contact> GetAll()
        {
            var list = Cache.Get<List<Contact>>(CacheKey);
            if (list != null) return list;

            list = new List<Contact>
            {
                new Contact { Id = 1, FirstName = "Bill", LastName = "Gates" },
                new Contact { Id = 2, FirstName = "Steve", LastName = "Jobs" },
                new Contact { Id = 3, FirstName = "Larry", LastName = "Page" },
                new Contact { Id = 3, FirstName = "Sergey", LastName = "Brin" }
            };

            Cache.Put(CacheKey, list);
            return list;
        }

        public Contact GetById(int id)
        {
            var list = GetAll();
            return list.FirstOrDefault(i => i.Id == id);
        }

        public void Save(Contact contact)
        {
            if (contact == null) throw new Exception("Can not save a null Contact.");

            var list = GetAll();

            if (contact.Id == 0)
                contact.Id = list.Max(i => i.Id) + 1;

            list.RemoveAll(i => i.Id == contact.Id);
            list.Add(contact);
            Cache.Put(CacheKey, list.OrderBy(i => i.Id).ToList());
        }

        public void Remove(int id)
        {
            var list = GetAll();
            list.RemoveAll(i => i.Id == id);
            Cache.Put(CacheKey, list);
        }
    }
}